home *** CD-ROM | disk | FTP | other *** search
- Path: crl.crl.com!not-for-mail
- From: smuegge@crl.com (Shad Muegge)
- Newsgroups: comp.lang.c
- Subject: A little shift to the left and a little shift to the right.
- Date: 12 Apr 1996 22:36:22 -0700
- Organization: CRL Network Services (415) 705-6060 [Login: guest]
- Message-ID: <4knegm$40d@crl.crl.com>
- NNTP-Posting-Host: crl.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Our trusty PL/M-to-C translator generated the C operators << and >>
- whenever it encountered the PL/M operators SHL and SHR.
-
- In one case the original coder had used these bit shifting operators
- to clear out the top nibble of a byte using the following code.
- (Actually this is the C code the translator generated less the
- proprietary variable names. :))
-
- x = ( ( y << 4 ) >> 4 );
-
- (The name of the coder will remain a secret, and yes I know a
- simple "& 0x0f" would be a more obvious solution. but the same
- problem is exhibited for any left-shift followed by a right-shift)
-
- Both the variables x and y are bytes ( unsigned chars ).
-
- The results of this code is the the value of y is assigned to
- x without any modification. The same results as simple assignment
- (x = y). It turns out that every C compiler I've tried ( Intel-C,
- Microsoft VC++, and gcc) exhibits this same behaviour.
- Looking at the assembly code generated by all three compilers the
- reason the shifts have no effect is because they do them with 32
- bit registers. So, when the bits are shifted to the left by 4 they
- aren't "lost" as one might expect. Then the right shift just
- returns all the bits to original position.
-
- By using a typecast two of the compilers (Intel-C and gcc) will
- do what the original coder intended, mask off the the top nibble of
- a byte. Microsoft's compiler just ignored the typecast and
- generated the same code as it did without the typecast.
-
- x = ( ( unsigned char ) ( y << 4 ) >> 4 );
-
- Also, seperating the two shifts into two statements all the compilers
- work as originally hoped.
-
- x = y << 4;
- x = x >> 4;
-
- Anyway, any experts in C want to tell me whether these compilers
- are just doing these operations correctly or incorrectly? Also,
- what about the fact that the Microsoft compiler ignores the typecast
- unlike Intel-C and gcc? Also, if any experts in human behaviour
- want to tell me why I care, I would appreciate that too.
-
- Shad
- smuegge@crl.com
-